package com.service;

import com.service.IBaiDuMapService;
import com.vo.NearFriend;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.BoundGeoOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class BaiduMapServiceImpl implements IBaiDuMapService {

    @Autowired
    private RedisTemplate redisTemplate;

    public void addData(String me,double x,double y){
        BoundGeoOperations city=redisTemplate.boundGeoOps("city");
        city.add(new Point(x,y),me);
    }

    /**
     * 添加测试数据，实际不移动的可以从数据库加读取，移动直接写redis,不存mysql
     */
    public void addData(){
        BoundGeoOperations city=redisTemplate.boundGeoOps("city");
        city.add(new Point(118.803805,32.060168),"南京");
        city.add(new Point(116.397039, 39.9077), "北京");
        city.add(new Point(113, 28.21), "长沙");
        city.add(new Point(113.16, 27.83), "株洲");

    }


    /**
     * 两个城市间的距离
     * @param city1
     * @param city2
     * @return
     */
    public double distance(String city1,String city2){
        try {
            BoundGeoOperations city=redisTemplate.boundGeoOps("city");
            System.out.println("distance==city:"+city);
            Distance distance=city.distance(city1,city2);
            return distance.getValue();  //两者距离，单位是米
        }catch(Exception e){
            return 0;
        }
    }

    public List<NearFriend> nearFriends(String me,double r,int limit){
        BoundGeoOperations city=redisTemplate.boundGeoOps("city");
        RedisGeoCommands.GeoRadiusCommandArgs commandArgs=RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs();
        commandArgs.includeDistance();  //结果包含距离
        commandArgs.includeCoordinates();  //结果包含 经纬度
        commandArgs.sortAscending(); //距离从近到远排序
        commandArgs.limit(limit+1); //返回多少个结果，因为包含自己
        GeoResults<RedisGeoCommands.GeoLocation> results=city.radius(me,new Distance(r), commandArgs);
        List list=new ArrayList();
        for (GeoResult<RedisGeoCommands.GeoLocation> result:results){
            RedisGeoCommands.GeoLocation location=result.getContent();  //位置信息
            Distance distance=result.getDistance();  //距离信息
            String name=(String)location.getName();  //城市的名字
            double x=location.getPoint().getX();
            double y=location.getPoint().getY();
            double juli=distance.getValue();
            if (me.equals(name)==false){
                list.add(new NearFriend(name,juli,x,y));
            }

        }
        return list;

    }





}
